<!-- 在线PDF预览
    引用样例：
    <preview-pdf url="http://192.168.20.181:9000/spa/123.pdf" />
-->
<template>
  <iframe
    v-if="url"
    ref="iframeRef"
    type="application/pdf"
    :src="'/pdfjs/web/viewer.html?file=' + url"
    frameborder="0"
    scrolling="no"
    :width="width"
    :height="height"
  ></iframe>
</template>

<script lang="ts" setup>
  import { useElementSize } from '@vueuse/core'
  import { nextTick, onMounted, ref, watch } from 'vue'

  export interface Props {
    url: string //pdf在线地址，不可使用本地地址
    width?: string
    height?: string
    isHeightAuto?: boolean //是否根据pdf自适应高度
  }

  const props = withDefaults(defineProps<Props>(), {
    width: '100%',
    height: '675px',
    isHeightAuto: false
  })

  const iframeRef = ref<HTMLIFrameElement>()
  const iframeViewerDOM = ref<HTMLElement>()

  const { height: viewerHeight } = useElementSize(iframeViewerDOM)

  watch(viewerHeight, async val => {
    await nextTick()
    iframeRef.value?.height && (iframeRef.value.height = Math.ceil(val) + 50 + 'px') //+50是为了防止出现滚动条
  })

  // 刷新iframe
  const refresh = () => {
    iframeRef.value?.contentWindow?.location.reload()
  }

  onMounted(() => {
    // 如果自动渲染高度就需要监听iframe的load事件，获取iframe的内容，然后获取内容中的viewer元素，获取高度
    if (props.isHeightAuto) {
      let iframeWin = iframeRef.value?.contentWindow
      iframeWin?.addEventListener('load', () => {
        iframeViewerDOM.value = iframeWin?.document.getElementById('viewer') as HTMLElement
      })
    }
  })
  defineExpose({ refresh })
</script>

<style scoped lang="less">
  iframe {
    border-radius: 10px;
  }
</style>
